package com.parq.ie.google.customsearch;

import java.util.Iterator;

import org.apache.log4j.Logger;
import org.w3c.dom.NodeList;

import com.parq.cs.crawl.CSCrawlerController;
import com.parq.cs.crawl.CSCrawlResult;
import com.parq.cs.db.CSDBProxy;

public class CSController {

	
	private static Logger log = Logger.getLogger(CSController.class);
	private static CSController instance;
	private static int numberOfRequests;
	
	
	protected CSController() {
	}

	public CSResult webSearch(String query) throws Exception {
		CSResult result = null;
		try {
			CSDBProxy db = new CSDBProxy();
			long searchid = db.searchDB(query);
			String resultsFeed = db.getResultsFeed(searchid);
			
			log.debug("DB:  " + resultsFeed);
			
			if (resultsFeed == null || resultsFeed.length() <= 0) {

				if (!requestAllowed())
					throw new Exception(
							"Number of requests exceeds allowed quota.");
				
				log.debug("Requesting from Google");
				resultsFeed = CSRequest.request(CSConfig.APP_KEY,
						CSConfig.APP_ID, query);
				
				log.debug("Google :  " + resultsFeed);
				searchid=db.addToDB(query,resultsFeed);
			}
			
			db.close();

			result = new CSResult(resultsFeed,searchid);
			numberOfRequests++;
		} catch (Exception e) {
			throw new Exception("Exception occurred while searching Web ", e);
		}

		return result;
	}

	public static CSController getInstance(int requestMade) throws Exception {
		if (instance == null) {
			instance = new CSController();
			numberOfRequests = requestMade;
		}
		return instance;
	}

	protected static boolean requestAllowed() {
		if (numberOfRequests < CSConfig.ALLOWED_NUMBER_OF_REQUESTS)
			return true;
		else
			return false;
	}

	
	public static void main (String [] args)throws Exception{
		CSController controller=CSController.getInstance(0);
		CSResult result=controller.webSearch(java.net.URLEncoder.encode("Abraham Lincolin"));
		
		System.out.println("Searching ... [searchid=" +result.getSearchid() + "]");
		
		System.out.println("Results Found = " + result.getNumberOfResults());
		NodeList list=result.getResults();
		
		for (int i=0;i<list.getLength();i++){
			System.out.println("\t " + i + ": " + list.item(i).getNodeValue());
		}
		
		
//		CSCrawlerController c=new CSCrawlerController(result);
//		
//		Iterator<CSCrawlResult> itr=c.getResults().iterator();
//		while(itr.hasNext()){
//			System.out.println(itr.next());
//		}
		
//		System.out.println("Searching Again ...");
//		result=controller.webSearch("Osama");
//		
//		System.out.println("Results Found = " + result.getNumberOfResults());
//		list=result.getResults();
//		
//		for (int i=0;i<list.getLength();i++){
//			System.out.println("\t " + i + ": " + list.item(i).getNodeValue());
//		}
		
	}
}
